package smartcase.endpoints;

import com.qcloud.cos.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import smartcase.base.auth.Verify;
import smartcase.base.ApiResponse;
import smartcase.base.ApiStandard;
import smartcase.base.file.TencentCosTool;
import smartcase.base.log.Log;
import smartcase.base.log.LogFactory;
import smartcase.dto.request.CheckHealthRequest;
import smartcase.dto.response.CheckHealthResponse;
import smartcase.model.Project;
import smartcase.service.CheckHealthService;

import java.io.IOException;
import java.net.URL;
import java.util.Optional;

import static smartcase.base.StandardKt.error;
import static smartcase.base.StandardKt.ok;

@RestController("smartHealthEndpoint")
public class HealthEndpoint {

  @Autowired CheckHealthService checkHealthService;

  @Autowired
  TencentCosTool cosTool;

  private Log log = LogFactory.getLog(HealthEndpoint.class);

  @GetMapping(value = "/getObjectAccessURL")
  public ApiResponse getObjectAccessURL(MultipartFile file) throws IOException {
    URL url = cosTool.getObjectAccessURL("bucketName", "main.png");
    return ok();
  }

  @GetMapping(value = "/uploadFile")
  public ApiResponse uploadFile(MultipartFile file) throws IOException {

    ObjectMetadata meta = new ObjectMetadata();
    meta.setHeader("customKey","customValue");
    cosTool.uploadFile("bucketName","main.png",file.getInputStream(),meta);

    return ok();
  }

  @GetMapping(value = "/echo")
  public ApiResponse checkHealth2() {

    CheckHealthResponse response = new CheckHealthResponse();
    response.setIsHealth(true);
    response.setServerIP("localhost");

    log.info("Hello World {}", "Cam");

    return ok();
  }

  @PostMapping(value = "/health/check")
  @Verify(group = "Default")
  public ApiResponse checkHealth(@RequestBody CheckHealthRequest request) {

    CheckHealthResponse response = new CheckHealthResponse();
    response.setIsHealth(true);
    response.setServerIP("localhost");

    log.info("Hello World {}", "Cam");

    return ok();
  }

  @PostMapping(value = "/health/check1")
  @Verify
  public ApiResponse checkHealth1(@RequestBody CheckHealthRequest request) {

    CheckHealthResponse response = new CheckHealthResponse();
    response.setIsHealth(true);
    response.setServerIP("localhost");

    Optional<Project> optional = checkHealthService.getProjectById("a");
    String hookName = optional.map(t -> t.getHook()).map(t -> t.getName()).orElse("");

    return error(ApiStandard.INTERNAL_SERVER_ERROR);
  }
}
